<template>
  <div id="cesiumContainer"></div>
</template>
<script setup>
import * as Cesium from "cesium";
import TOKEN from "@/utils/cesium/token.js";

onMounted(() => {
  Cesium.Ion.defaultAccessToken = TOKEN;
  // 实例化
  const viewer = new Cesium.Viewer("cesiumContainer", {});

  /**
   * 经纬高度 转 空间直角坐标
   * @param longitude 经度
   * @param latitude  纬度
   * @param height  高度
   * @return 空间直角坐标
   */
  function fn01(longitude, latitude, height) {
    const cartesian3 = Cesium.Cartesian3.fromDegrees(
      longitude,
      latitude,
      height
    ); // 经度、纬度、高度
    console.log("笛卡尔坐标 cartesian", cartesian3);
    return cartesian3;
  }

  // 空间直角坐标系 转 经纬高度
  function fn02(cartesian3) {
    // 1. 笛卡尔坐标 转弧度坐标
    const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
    console.log("弧度坐标 cartographic", cartographic);
    // 2. 弧度坐标转（角坐标）经纬度、高度
    const longitude = Cesium.Math.toDegrees(cartographic.longitude);
    const latitude = Cesium.Math.toDegrees(cartographic.latitude);
    // 3. 得到 经度、纬度、高度
    console.log(longitude, latitude, cartographic.height);
    return { longitude, latitude, height: cartographic.height };
  }

  fn02(fn01(110, 20, 30));

  
  const handelCartesian2ToCartesian3 = () => {
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (event) {
      const cartesian2 = event.position;
      console.log("屏幕坐标（平面坐标系cartesian2）", event.position);
      const cartesian3 = viewer.scene.globe.pick(
        viewer.camera.getPickRay(cartesian2),
        viewer.scene
      );
      console.log("空间坐标系（笛卡尔坐标系cartesian3）", cartesian3);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  };
 

  const handelCartesian3ToCartesian2 = () => {
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (event) {
      const cartesian = event.position;
      console.log("屏幕坐标（平面坐标系cartesian2）", event.position);
      const cartesian3 = viewer.scene.globe.pick(
        viewer.camera.getPickRay(cartesian),
        viewer.scene
      );
      console.log("空间坐标系（笛卡尔坐标系cartesian3）", cartesian3);
      const cartesian2 = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
        viewer.scene,
        cartesian3
      );
      console.log("转换后：屏幕坐标（平面坐标系cartesian2）", cartesian2);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  };

  handelCartesian3ToCartesian2();
});
</script>

<style scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
}
</style>
